package com.zyg.util;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zyg.common.ResultCode;
import com.zyg.model.Result;
import com.zyg.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * jwt工具类型
 */

@Slf4j
@Component
public class JWTUtil {

    // token秘钥
    private static String tokenSecret = "zyg-secret";

    // 过期时间 1000*60*60表示为一个小时
    private static Integer tokenOverdueTime = 1000*60*60*3;


    public static Result createToken(String tokenInfo) {
        try {
            Date iatDate = new Date();
            Calendar nowTime = Calendar.getInstance();
            nowTime.add(Calendar.MILLISECOND, tokenOverdueTime);
            Date expiresDate = nowTime.getTime();
            Map<String, Object> map = new HashMap<>();
            map.put("alg", "HS256");
            map.put("typ", "JWT");
            String token = JWT.create().withHeader(map)
                    .withClaim("iss", "Service")
                    .withClaim("dataInfo", tokenInfo)//添加token的信息到token中
                    .withIssuedAt(iatDate)
                    .withExpiresAt(expiresDate)
                    .sign(Algorithm.HMAC256(tokenSecret));
            log.info("---生成token成功！---");
            Map tokenMap = new HashMap();
            tokenMap.put("token",token);
            tokenMap.put("tokenOverdueTime",System.currentTimeMillis() + tokenOverdueTime);
            return new Result().initSuccess(tokenMap);
        } catch (Exception e) {
            log.error("---生成token失败！：", e);
            return new Result().initCodeAndMsg(ResultCode.INVALID_TOKEN);
        }
    }

    public static Map<String, Claim> verifyToken(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(tokenSecret)).build();
        DecodedJWT jwt = verifier.verify(token);
        return jwt.getClaims();
    }

    public static Result getTokenDataInfoJson(String token) {
        try {
            Map<String, Claim> claims = verifyToken(token);
            Claim tokenDataInfo = claims.get("dataInfo");
            if (!Objects.isNull(tokenDataInfo) && !Objects.equals("", tokenDataInfo.asString())) {
                UserInfo userInfo = JSON.parseObject(tokenDataInfo.asString(),UserInfo.class);
                return new Result().initSuccess(userInfo);
            }
            else {
                return new Result().initSuccess();
            }
        } catch (Exception e) {
            log.error("---获取token dataInfo异常：", e);
            return new Result().initCodeAndMsg(ResultCode.INVALID_TOKEN);
        }
    }

    public static UserInfo getTokenDataInfo(String token) {
        try {
            Map<String, Claim> claims = verifyToken(token);
            Claim tokenDataInfo = claims.get("dataInfo");
            if (!Objects.isNull(tokenDataInfo) && !Objects.equals("", tokenDataInfo.asString())) {
                UserInfo userInfo = JSON.parseObject(tokenDataInfo.asString(),UserInfo.class);
                return userInfo;
            }
            else {
                return null;
            }
        } catch (Exception e) {
            log.error("---获取token dataInfo异常：", e);
            return null;
        }
    }

}
